package com.sky.employee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.employee.mapper.EmployeeMapper;
import com.sky.employee.service.EmployeeService;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.result.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.sky.constant.PasswordConstant.DEFAULT_PASSWORD;
import static com.sky.constant.StatusConstant.ENABLE;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        QueryWrapper<Employee> wrapper = new QueryWrapper<Employee>().eq("username", username);
        Employee employee = employeeMapper.selectOne(wrapper);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //将密码用md5进行加密
        // password=DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

//    /**
//     *
//     * @param employeeDTO
//     */
//    @Override
//    public void save(EmployeeDTO employeeDTO) {
//        Employee employee = new Employee();
//        //将DIO类转成employee,用属性拷贝
//        BeanUtils.copyProperties(employeeDTO,employee);
//        //之后补全属性
//        //账号状态
//        employee.setStatus(ENABLE);
//        //密码
//        employee.setPassword(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
//        //创建时间和更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //用进程id来记录当前操作人的id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employeeMapper.insert(employee);
//    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        String name = employeePageQueryDTO.getName();
        //将分页条件构造交给了EmployeePageQueryDTO里面的toPage()方法

//        //wrapper.like(name != null, "name", name);
//
//        Page<Employee> page = Page.of(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
//        page.addOrder(new OrderItem("create_time", false));
        Page<Employee> page = employeePageQueryDTO.toPage();
        Page<Employee> employeePage = lambdaQuery()
                //相当于代替了上面的wrapper构造条件
                .like(StrUtil.isNotBlank(name), Employee::getName, name)
                .page(page);

        //Page<Employee> employeePage = employeeMapper.selectPage(new Page<>(1, 2), wrapper);
        return new PageResult(employeePage.getSize(), employeePage.getRecords());
    }

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        LambdaUpdateWrapper<Employee> LambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper
                .eq(Employee::getId, passwordEditDTO.getEmpId())
                .eq(Employee::getPassword, passwordEditDTO.getOldPassword());
        Employee employee = Employee.builder()
                .id(passwordEditDTO.getEmpId())
                .password(passwordEditDTO.getNewPassword())
                .build();
        int result=employeeMapper.update(employee, LambdaUpdateWrapper);
        if(result==0){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
    }


}
